package org.bot.server.event.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.bot.server.event.mapper.BotEventMapper;
import org.bot.server.event.service.EventService;
import org.bot.server.utils.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author 沧月
 * @create 0002 2023/11/2 17:56
 * @description <description class purpose>
 */
@Service
public class EventServiceImpl implements EventService {

    @Autowired
    private ResourceLoader resourceLoader;

    @Value("${bot.mode}")
    private String mode;

    @Autowired
    BotEventMapper botEventMapper;

    @Override
    public List<Map<String, Object>> getEventList(String clientId) {
        if (Mode.LOCATION.getMode().equals(mode)) {
            clientId = Mode.LOCATION.getMode();
        }
        return botEventMapper.list(clientId);
    }

    @Override
    public JSONObject eventConfig(String eventName) {
        if (eventName == null) {
            eventName = "default";
        }
        Resource resource = resourceLoader.getResource("classpath:eventConfig/" + eventName + ".json");
        if (!resource.exists()) {
            resource = resourceLoader.getResource("classpath:eventConfig/default.json");
        }
        try {
            InputStream inputStream = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder str = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
            return JSONObject.parseObject(str.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
